package com.canbot.u05.activity.shoppingGuide.advisory;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.ChooseAudioActivity;
import com.canbot.u05.activity.shoppingGuide.ShoppingChooseAudioActivity;
import com.canbot.u05.bean.AdvisoryQA;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.RouteRecordDialog;
import com.canbot.u05.view.UsherModeRecordDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 选择答案回复类型界面
 */
public class SelectAnswerTypeActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private final static String TAG = "SelectAnswerTypeActivity";

        private static final int REQUEST_AUDIO = 101;

        private static final int REQUEST_TEXT_TO_SPEECH = 102;

        private static final int REQUEST_RECORD = 103;

        private RelativeLayout rlLocalSpeech;

        private RelativeLayout rlTextToSpeech;

        private RelativeLayout rlRecord;

        private AdvisoryQA advisoryQA;

        private boolean isEdit;

        private RouteRecordDialog usherModeRecordDialog;

        private String fileName;

        private String audioPath;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_select_answer_type);

                String js = getIntent().getStringExtra("data");
                isEdit = getIntent().getBooleanExtra("isExit", false);
                audioPath = getIntent().getStringExtra("path");

                if (!TextUtils.isEmpty(js)) {
                        Logger.e(TAG, "接收数据=" + js);
                        advisoryQA = JSON.parseObject(js, AdvisoryQA.class);
                }
                initView();
        }


        private void initView() {
                rlLocalSpeech = (RelativeLayout) findViewById(R.id.rl_local_speech);
                rlTextToSpeech = (RelativeLayout) findViewById(R.id.rl_text_to_speech);
                rlRecord = (RelativeLayout) findViewById(R.id.rl_record);

                rlLocalSpeech.setOnClickListener(this);
                rlTextToSpeech.setOnClickListener(this);
                rlRecord.setOnClickListener(this);

                if (isEdit) {
                        switch (advisoryQA.getType()) {
                                case 0:
                                        rlLocalSpeech.setSelected(true);
                                        break;
                                case 1:
                                        rlTextToSpeech.setSelected(true);
                                        break;
                                case 2:
                                        rlRecord.setSelected(true);
                                        break;
                        }
                }
        }

        /**
         * 返回
         *
         * @param view
         */
        public void back(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        /**
         * 选择完语音后提交
         *
         * @param view
         */
        public void complete(View view) {
                commitDataToPad();
        }

        private Dialog dialogLoading;


        /**
         * 提交数据到胸口
         */
        private void commitDataToPad() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.data_upload));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                String values = JSON.toJSONString(advisoryQA);
                Logger.e(TAG, "上传数据" + values);
                Call<String> call = null;
                if (isEdit) {
                        call = salesApi.editAdvisory(values);
                        Logger.e(TAG, "编辑提交");
                }
                else {
                        call = salesApi.addAdvisory(values);
                        Logger.e(TAG, "新建提交");
                }
                call.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        String body = response.body();

                                        Logger.e(TAG, "网络返回的数据" + body + "");
                                        Intent intent2 = new Intent(SelectAnswerTypeActivity.this, SettingAdvisoryActivity.class);
                                        startActivity(intent2);
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                t.fillInStackTrace();
                                Logger.e(TAG, "网络返回的数据错误信息 " + call.toString());
                                ToastTools.newInstance(SelectAnswerTypeActivity.this).showText(getString(R.string.submit_failure));

                        }
                });
        }


        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.rl_local_speech:

                                Intent i = new Intent(SelectAnswerTypeActivity.this, ChooseAudioActivity.class);
                                i.putExtra("path", audioPath);
                                if (isEdit){
                                        if (advisoryQA.getType() == 0){
                                                i.putExtra("voice", advisoryQA.getAnswer());
                                        }

                                }

                                startActivityForResult(i, REQUEST_AUDIO);

                                break;
                        case R.id.rl_text_to_speech:
                                //文字转语音
                                Intent intent2 = new Intent(SelectAnswerTypeActivity.this, com.canbot.u05.activity.shoppingGuide.sales.TextToSpeechActivity.class);
                                if (isEdit){
                                        if (advisoryQA.getType() == 1){
                                                intent2.putExtra("voice", advisoryQA.getAnswer());
                                        }
                                }
                                startActivityForResult(intent2, REQUEST_TEXT_TO_SPEECH);

                                break;
                        case R.id.rl_record:
                                //录音
                                record();

                                break;
                        case R.id.record_dialog_finish:
                                fileName = usherModeRecordDialog.ok();
                                Logger.e("test", "fileName" + fileName);
                                usherModeRecordDialog.setTime(SelectAnswerTypeActivity.this.getString(R.string.uploading_please_wait));
                                Logger.d("SpeechSetupActivity", "录音的文件名：" + fileName);
                                uploadFile();

                                break;
                        case R.id.record_dialog_cancle:
                                usherModeRecordDialog.no();
                                //finish();
                                usherModeRecordDialog.dismiss();
                                Logger.d("SpeechSetupActivity", "录音的文件名：" + fileName);
                                break;
                        default:
                                break;
                }

                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                if (requestCode == REQUEST_AUDIO && resultCode == RESULT_OK ) {
                        boolean isExist = data.getBooleanExtra("isChecked", false);
                        String path = data.getStringExtra("path");  //path为全路径
                        Logger.e("SelectAnswerTypeActivity", "选中的语音路径 ：" + path);
                        rlLocalSpeech.setSelected(true);
                        rlRecord.setSelected(false);
                        rlTextToSpeech.setSelected(false);
                        advisoryQA.setType(0);
                        advisoryQA.setAnswer(path);
                }
                else if (requestCode == REQUEST_TEXT_TO_SPEECH && resultCode == RESULT_OK) {
                        boolean isExist = data.getBooleanExtra("isChecked", false);
                        String content = data.getStringExtra("ttsResult");
                        Logger.e("SelectAnswerTypeActivity", "输入回答为 ：" + content);
                        advisoryQA.setType(1);
                        advisoryQA.setAnswer(content);
                        rlLocalSpeech.setSelected(false);
                        rlRecord.setSelected(false);
                        rlTextToSpeech.setSelected(true);

                }
        }

        /**
         * 进入录音
         */
        private void record() {
                if (usherModeRecordDialog == null) {
                        //点击语音录入图标
                        usherModeRecordDialog = new RouteRecordDialog(this, RouteRecordDialog.USHER_MODE);
                        usherModeRecordDialog.setFinishClickListener(this);
                        usherModeRecordDialog.setCancleClickListener(this);
                        setDialogWindowAttr(usherModeRecordDialog, this);
                        usherModeRecordDialog.show();
                }
                else {
                        usherModeRecordDialog.show();
                }

        }

        //上传到机器人头部的某个文件夹下
        private String url = IpMsgConst.HTTP_URL + "uploadRecord";

        private void uploadFile() {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("audiofile", new File(UsherModeRecordDialog.RECORD_FILE_DIR, fileName));
                hashMap.put("path", fileName);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {
                                Logger.e(TAG, result + "上传成功");
                                SPUtils.saveBoolean(SelectAnswerTypeActivity.this, "isTTS", false);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                usherModeRecordDialog.cancel();
                                                ToastTools.newInstance(SelectAnswerTypeActivity.this).showText(getString(R.string.upload_complete));
                                                String path = fileName;
                                                Logger.e("SelectAnswerTypeActivity", "录音文件路径 ：" + path);
                                                rlLocalSpeech.setSelected(false);
                                                rlRecord.setSelected(true);
                                                rlTextToSpeech.setSelected(false);
                                                advisoryQA.setType(2);
                                                advisoryQA.setAnswer(path);
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {

                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                usherModeRecordDialog.cancel();
                                                ToastTools.newInstance(SelectAnswerTypeActivity.this).showText(getString(R.string.upload_failed));
                                        }
                                });
                        }
                });
        }

        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                dlg.setCancelable(false);
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x536);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x436);
                dlg.getWindow().setAttributes(lp);
        }
        private static final int TIMEOUT = 100;//超时时间100s
        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                isEdit = false;
                super.onDestroy();
        }
}
